<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" :width="800">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref, onMounted } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from './data';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { updateJob, addJob } from '/@/api/job/job';
import { getGroupList } from '/@/api/config/group'

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
const groups = ref([])
onMounted(async () => {
  groups.value = await getGroups()
})

const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
  labelWidth: 90,
  baseColProps: { span: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
});

const getGroups = async () => {
  const list = await getGroupList()
  const envs = Array.from(new Set(list.map(o => o.env)))
  let options: any = []
  for (const env of envs) {
    options.push({
      label: env,
      options: list.filter(o => o.env == env).map(o => { return { label: o.name, value: o.id } })
    })
  }
  return options
}

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields();
  setModalProps({ confirmLoading: false });
  isUpdate.value = !!data?.isUpdate;
  if (unref(isUpdate)) {
    setFieldsValue({
      ...data.record,
    });
    updateSchema([
      {
        field: 'jobName',
        componentProps: {
          disabled: true
        }
      },
      {
        field: 'jobGroup',
        componentProps: {
          disabled: true
        }
      }
    ])
  }else{
    updateSchema([
      {
        field: 'jobName',
        componentProps: {
          disabled: false
        }
      },
      {
        field: 'jobGroup',
        componentProps: {
          disabled: false
        }
      }
    ])
  }
  updateSchema({
    field: 'groupId',
    componentProps: {
      options: groups
    }
  })
});


async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    if (unref(isUpdate)) {
      await updateJob(values);
    } else {
      await addJob(values);
    }
    closeModal();
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>